from PyDialog import PyDialog
import etgui,CmdNo,string,regex,regsub,FlexLMErrors
from etgui import *
cId=12121

class LicensedTool:
	def __init__(self,name='',feature='',*aliases):
		self.name=name
		self.feature=feature
		self.aliases=[name,feature]+list(aliases)
		self.id=-1
class LicensedTools:
	def __init__(self,*tools):
		self.tools=tools
		for i in range(len(self.tools)):
			self.tools[i].id=i
	def GetId(self,tool):
		for i in range(len(self.tools)):
			if tool in self.tools[i].aliases:
				return i
		return -1
	def GetToolByName(self,tool):
		return self.tools[self.GetId(tool)]
	def GetToolNames(self):
		return map(lambda tool: tool.name, self.tools)
	def GetToolById(self,id):
		return self.tools[id]
gLicences=LicensedTools(
	LicensedTool('SNiFF+','SNiFF'),
	LicensedTool('C++ Parser','C++','sniffparser'),
	LicensedTool('Java Parser','Java','sniffjava'),
	LicensedTool('Fortran Parser','Fortran','sniff_fortran_new','sniff_fortran'),
	LicensedTool('IDL Parser','IDL','sniffidl'),
#	LicensedTool('All Features','ALL'),
	
)
class MyDialog(PyDialog):
	title="Licenses"
	in_update=0
	def __init__(self,tool,msg):
		self.tool=tool
		PyDialog.__init__(self)
		self.checker=LicenseChecker()
	def MakeContent(self):
		self.exp= HBox(
			items=[Filler(gPoint0)]
		)
		self.header= 				AlignBox(
					eVObjHCenter,
					Filler(gPoint0),
				)

		self.scr=Scroller(self.exp)
		menu=Menu(dimall=0)
		self.popup=PopupButton(id=cId,menu=menu)
		id=0
		for s in gLicences.GetToolNames():
			menu.AppendItem(s,id)
			id=id+1
		self.ShowToolInfo(self.tool)
		return VBox(
			align=eVObjHCenter|eVObjHExpand|eVObjVExpand,
			items=(
				Form(
					align=eVObjVBase,
					middle=0,
					flags=eVObjVFixed,
					items=(
						"Show license status for",self.popup,
						),
				),
				self.header,
				HBox(
					gap=gPoint0,
					align=eVObjHExpand|eVObjVExpand,
					items=(self.scr,Filler(Point(0,500))),
				),
				#Separator(),
				Filler(Point(500,0),flags=eVObjVFixed),
				HBox(
					gap=gPoint8,
					align=eVObjHEqual|eVObjVBase,
					items= (
						ActionButton(CmdNo.cIdOk,"OK",1),
						ActionButton(CmdNo.cIdApply,"Update Info")
					)
				)
			)
		)
	def Control(self,id,part,val):
		if id==CmdNo.cIdOk:
			self.Finish()
			return 0
		elif id==CmdNo.cIdApply:
			self.UpdateInfo()
			return 1
		elif id==cId:
			self.UpdateInfo(self.GetSelectedTool())
			return 1
		return 0
	def GetSelectedTool(self):
		return gLicences.GetToolById(self.popup.GetValue())
	def InUpdate(self):
		return self.in_update
	def MakeText(self):
		self.in_update=1
		try:
			self.checker.Check()
		finally:
			self.in_update=0
		return MultilineTextItem(self.checker.GetInfo(),-1,gFixedFont)
	def MakeHeader(self):
		return MultilineTextItem(self.checker.GetHeader())
	def ShowToolInfo(self,toolname):
		tool=gLicences.GetToolByName(toolname)
		self.UpdateInfo(tool)
	def UpdateInfo(self,tool=None):
		if tool:
			self.checker.SetTool(tool)
		else:
			tool=self.checker.GetTool()
		if self.GetSelectedTool()!=tool:
			self.popup.SetValue(tool.id)
			self.popup.Update()
		self.exp.SetAt(0,self.MakeText())
		self.exp.Update()
		self.scr.Update()
		self.header.SetAt(0,self.MakeHeader())
		self.header.Update()
		self.header.Update()
	def Restore(self):
		self.Finish()
	def Finish(self):
		"""Show at most one dialog"""
		global gLicenseDialog,gLizenseDoneFunc
		gLicenseDialog=None
		if gLizenseDoneFunc:
			f=gLizenseDoneFunc
			gLizenseDoneFunc=None # dont show it anymore
			f()
def escape(str):
	return regsub.gsub("@","@@",str)
class LicenseChecker:
	def SetTool(self,tool):
		self.tool=tool
		self.feature=tool.feature
	def GetTool(self):
		return self.tool
	def Check(self):
		self.no_such_feature=[]
		self.info=''
		self.header=''
		fn=SLicenseGetFeatureNames(self.feature)
		result=self.DoCheck(fn)
		if result:
			self.SetHeader("You @Bhave@B a license for @B%s@B!" %self.tool.name)
		else:
			self.SetHeader("You @Bdon't have@B a license for @B%s@B!" %self.tool.name)
		return result
	def SetInfo(self,info):
		self.info=self.info+info
	def GetInfo(self):
		return string.strip(self.info)
	def SetHeader(self,info):
		self.header=info
	def GetHeader(self):
		return string.strip(self.header)
	def DoCheck(self,fn):
		v=SLicenseGetVersion()
		#v="2.3"
		#print fn
		if not fn:
			self.SetInfo("No %s" %self.feature)
			return 1
		else:
			fail=""
			for subfeature in fn:
				(ok,info,msg)=self.CheckSubFeature(v,subfeature)
				#print self.feature,subfeature,ok
				if ok:				
					self.SetInfo(info+msg)
					return 1
				fail=fail+info+msg
			self.SetInfo(fail+self.GetAllSpecial())
			return 0
	def CheckSubFeature(self,v,subfeature):
		fn=[subfeature]
		f=LMFeature(self.feature,v,fn)
		f.Refresh()
		msg=f.GetLicenseMsg()
		if regex.search("Feature:",msg)>0:
			msg=escape(msg)
#			msg=regsub.gsub("  \([A-Za-z]+\):[^<]+<\([^>]+\)>","\\1:\t@B\\2@B",msg)
#			msg=regsub.gsub("    \(.*\)","\t@B\\1@B",msg)
			msg=regsub.gsub("<\([^>]+\)>","@B\\1@B",msg)
			msg=regsub.gsub("^    \(.*\)","    @B\\1@B",msg)
		else:
			msg=''
		if not f.Ok():
			return 0,self.TranslateError(f.LastError(),subfeature),msg
		info= "\n@BYou got the feature @I%s@I@B\n\n" %subfeature
		f.Free()
		return 1,info,msg

	reg=regex.compile("\([^(]+\)(\(-[0-9]+\)[^)]+)\(.*\)")
	def TranslateError(self,errormsg,subfeature):
		reg=self.reg
		if reg.match(errormsg)<=0:
			return "@B%s@B" %escape(errormsg)
		no=string.atoi(reg.group(2))
		details=reg.group(3)
		if self.HandleSpecial(subfeature,no,details):
			return ''
		explain=FlexLMErrors.GetErrorString(no)
		explain=escape(explain)
		if details:
			details=": "+details
		result="\n@BYou can @Unot@U get the feature @I"+subfeature+"@I:@B\n\n"
		return result+"@B@I%s@I@B%s\n%s\n" %(reg.group(1),details,explain) #+ "\n"+errormsg
	def HandleSpecial(self,subfeature,errno,details):
		if errno==-5 and details=='':
			self.no_such_feature.append(subfeature)
			return 1
		return 0
	def GetAllSpecial(self):
		if self.no_such_feature:
			m="\n@BYou don't have any of the following license features:@B\n\t"
			m=m+string.join(self.no_such_feature,'\n\t')
			return m
		return ''
		
gLicenseDialog=None
gLicenseInfo=None
gLiceseUpdate=0
gLizenseDoneFunc=None
def Show(tool,msg):
	global gLicenseDialog,gLicenseInfo,gLiceseUpdate
	if gLicenseDialog:
		if gLicenseDialog!=1 and not gLicenseInfo.InUpdate():
			gLicenseInfo.ShowToolInfo(tool)
			gLicenseDialog.ShowUnderMouse()
	else:
		gLicenseDialog=1
		ok=0
		try:
			gLicenseInfo=MyDialog(tool,msg)
			gLicenseDialog= etgui.ShowDialog(gLicenseInfo)
			ok=1
		finally:
			if not ok:
				gLicenseDialog=None
def Hide():
	if gLicenseDialog and gLicenseDialog!=1:
		try:
			gLicenseDialog.Hide()
		except:
			pass
